/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MobileCLient;

import Core.IConnectionHandler;
import Core.IConnectionListener;
import Core.WriterThread;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

/**
 *
 * @author Mr Bao
 */
public class ConnectionHandler implements IConnectionHandler {

    protected PrintStream outToSlave;
    protected DataInputStream inFromSlave;
    protected Socket socket;
    protected IConnectionListener listener;
    protected ReaderThread reader;
    protected WriterThread writer;

    public ConnectionHandler(Socket socket) throws IOException {
        this.socket = socket;
        outToSlave = new PrintStream(this.socket.getOutputStream());
        inFromSlave = new DataInputStream(this.socket.getInputStream());
        reader = new ReaderThread(inFromSlave, this);
        writer = new WriterThread(outToSlave);
        writer.start();
    }

    public void QueueMessage(String message) {
        writer.QueueMessage(message);
    }

    public void SendImmediately(String message) {
        outToSlave.println(message);
        outToSlave.flush();
    }

    public void Shutdown(boolean notify) {
        reader.Halt();
        writer.Halt();
        writer.FlushOutputQueue();
        try {
            socket.close();
            inFromSlave.close();
            outToSlave.close();
        } catch (Exception e) {
        }
        listener.SocketClosed();
    }

    public void SetListener(IConnectionListener listener) {
        this.listener = listener;
        reader.SetListener(listener);
        reader.start();
    }
}
